﻿using System;
using System.ComponentModel;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Globalization;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;

namespace SIMSProject.WebParts.ContainerWebPart
{
    [ToolboxItemAttribute(false)]
    public class ContainerWebPart : WebPart
    {
        protected Control userControl;

        /// <summary>
        ///   Override the chrome type to hide the border
        /// </summary>
        public override PartChromeType ChromeType
        {
            get { return PartChromeType.None; }
            set { base.ChromeType = value; }
        }

        /// <summary>
        ///   Contains the path to the user control to load
        /// </summary>
        [WebBrowsable]
        [WebDisplayName("User Control Path")]
        [Personalizable(PersonalizationScope.Shared)]
        public string UserControlPath { get; set; }

        /// <summary>
        ///   Load the user control required
        /// </summary>
        protected override void CreateChildControls()
        {
            base.CreateChildControls();

            if (SPContext.Current.IsDesignTime)
            {
                Controls.Clear();
                Controls.Add(new Literal
                {
                    Text =
                        @"Container WebPart" +
                        (string.IsNullOrEmpty(UserControlPath)
                             ? " (No User Control Specified)"
                             : string.Format(CultureInfo.InvariantCulture, " ({0})", UserControlPath))
                });
            }
            else
            {
                if (WebPartManager.DisplayMode == WebPartManager.BrowseDisplayMode && !string.IsNullOrEmpty(UserControlPath))
                {
                    try
                    {
                        userControl = Page.LoadControl(UserControlPath);
                        Controls.Add(userControl);
                    }
                    catch (Exception ex)
                    {
                        Controls.Clear();
                        Controls.Add(new Literal { Text = string.Format("Container WebPart ({0})", ex.Message) });
                    }
                }
                else
                {
                    Controls.Clear();
                    Controls.Add(new Literal
                    {
                        Text =
                            @"Container WebPart" +
                            (string.IsNullOrEmpty(UserControlPath)
                                 ? " (No User Control Specified)"
                                 : string.Format(" ({0})", UserControlPath))
                    });
                }
            }
        }
    }
}
